

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="叶飞">
  <meta name="keywords" content="">
  
    <meta name="description" content="1 leetcode 796 123456796. 旋转字符串给定两个字符串, s 和 goal。如果在若干次旋转操作之后，s 能变成 goal ，那么返回 true 。s 的 旋转操作 就是将 s 最左边的字符移动到最右边。 例如, 若 s &#x3D; &amp;#x27;abcde&amp;#x27;，在旋转一次之后结果就是&amp;#x27;bcdea&amp;#x27; 。  解决  1return len(s) &#x3D;&#x3D; len">
<meta property="og:type" content="article">
<meta property="og:title" content="Leetcode796.KMP算法">
<meta property="og:url" content="http://example.com/2022/04/07/20220407-Leetcode796-KMP%E7%AE%97%E6%B3%95/index.html">
<meta property="og:site_name" content="博客">
<meta property="og:description" content="1 leetcode 796 123456796. 旋转字符串给定两个字符串, s 和 goal。如果在若干次旋转操作之后，s 能变成 goal ，那么返回 true 。s 的 旋转操作 就是将 s 最左边的字符移动到最右边。 例如, 若 s &#x3D; &amp;#x27;abcde&amp;#x27;，在旋转一次之后结果就是&amp;#x27;bcdea&amp;#x27; 。  解决  1return len(s) &#x3D;&#x3D; len">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/img/20220407-Leetcode796-KMP%E7%AE%97%E6%B3%95.assets/v2-2967e415f490e03a2a9400a92b185310_720w.jpg">
<meta property="og:image" content="http://example.com/img/20220407-Leetcode796-KMP%E7%AE%97%E6%B3%95.assets/v2-7dc61b0836af61e302d9474eeeecfe83_720w.jpg">
<meta property="og:image" content="http://example.com/img/20220407-Leetcode796-KMP%E7%AE%97%E6%B3%95.assets/v2-372dc6c567ba53a1e4559fdb0cb6b206_720w.jpg">
<meta property="og:image" content="http://example.com/img/20220407-Leetcode796-KMP%E7%AE%97%E6%B3%95.assets/v2-49c7168b5184cc1744459f325e426a4a_720w.jpg">
<meta property="og:image" content="http://example.com/img/20220407-Leetcode796-KMP%E7%AE%97%E6%B3%95.assets/v2-d6c6d433813595dce5aad08b40dc0b72_720w.jpg">
<meta property="og:image" content="http://example.com/img/20220407-Leetcode796-KMP%E7%AE%97%E6%B3%95.assets/v2-6d6a40331cd9e44bfccd27ac5a764618_720w.jpg">
<meta property="og:image" content="http://example.com/img/20220407-Leetcode796-KMP%E7%AE%97%E6%B3%95.assets/v2-ce1d46a1e3603b07a13789b6ece6022f_720w.jpg">
<meta property="og:image" content="http://example.com/img/20220407-Leetcode796-KMP%E7%AE%97%E6%B3%95.assets/v2-c5ff4faaab9c3e13690deb86d8d17d71_720w.jpg">
<meta property="article:published_time" content="2022-04-06T23:19:54.000Z">
<meta property="article:modified_time" content="2022-04-07T02:30:10.795Z">
<meta property="article:author" content="叶飞">
<meta property="article:tag" content="KMP">
<meta property="article:tag" content="字符串">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://example.com/img/20220407-Leetcode796-KMP%E7%AE%97%E6%B3%95.assets/v2-2967e415f490e03a2a9400a92b185310_720w.jpg">
  
  
  
  <title>Leetcode796.KMP算法 - 博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>No Tomorrow</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Leetcode796.KMP算法"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        叶飞
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-04-07 07:19" pubdate>
          星期四, 四月 7日 2022, 7:19 早上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          <!-- compatible with older versions-->
          3.2k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          <!-- compatible with older versions-->
          27 分钟
        
      </span>
    

    
    
      
        <span id="leancloud-page-views-container" class="post-meta" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="leancloud-page-views"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Leetcode796.KMP算法</h1>
            
            
              <div class="markdown-body">
                
                <h2 id="1-leetcode-796"><a class="markdownIt-Anchor" href="#1-leetcode-796"></a> 1 leetcode 796</h2>
<figure class="highlight tex"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs tex">796. 旋转字符串<br>给定两个字符串, s 和 goal。如果在若干次旋转操作之后，s 能变成 goal ，那么返回 true 。<br><br>s 的 旋转操作 就是将 s 最左边的字符移动到最右边。 <br><br>例如, 若 s = &#x27;abcde&#x27;，在旋转一次之后结果就是&#x27;bcdea&#x27; 。<br></code></pre></td></tr></table></figure>
<ul>
<li>解决</li>
</ul>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">return</span> <span class="hljs-built_in">len</span>(s) == <span class="hljs-built_in">len</span>(goal) &amp;&amp; strings.Contains(s+s, goal)<br></code></pre></td></tr></table></figure>
<ul>
<li>s+s 包含了所有通过旋转可以得到的字符串</li>
</ul>
<h2 id="2-字符串匹配算法kmp"><a class="markdownIt-Anchor" href="#2-字符串匹配算法kmp"></a> 2 字符串匹配算法KMP</h2>
<p>顺便好好掌握一下KMP算法吧</p>
<h3 id="字符串匹配问题"><a class="markdownIt-Anchor" href="#字符串匹配问题"></a> 字符串匹配问题</h3>
<p>所谓字符串匹配，是这样一种问题：“字符串 P 是否为字符串 S 的子串？如果是，它出现在 S 的哪些位置？” 其中 S 称为<strong>主串</strong>；P 称为<strong>模式串</strong>。下面的图片展示了一个例子。</p>
<p><img src="/img/20220407-Leetcode796-KMP%E7%AE%97%E6%B3%95.assets/v2-2967e415f490e03a2a9400a92b185310_720w.jpg" srcset="/img/loading.gif" lazyload alt="img"></p>
<h3 id="21-前置思路"><a class="markdownIt-Anchor" href="#21-前置思路"></a> 2.1 前置思路</h3>
<ul>
<li>暴力算法Brute-Force
<ul>
<li>复杂度<code>O(mn)</code></li>
</ul>
</li>
</ul>
<blockquote>
<p>利用已知的错误信息,从之前的错误中获取信息</p>
</blockquote>
<p><img src="/img/20220407-Leetcode796-KMP%E7%AE%97%E6%B3%95.assets/v2-7dc61b0836af61e302d9474eeeecfe83_720w.jpg" srcset="/img/loading.gif" lazyload alt="img"></p>
<ul>
<li>经验: 匹配从第r个位置失败,那么之前的(r-1)个连续字符都是匹配
<ul>
<li>主串的某一个子串 等于  模式串的某一个前缀</li>
</ul>
</li>
</ul>
<blockquote>
<p>跳过不可能成功的字符串比较</p>
</blockquote>
<p><img src="/img/20220407-Leetcode796-KMP%E7%AE%97%E6%B3%95.assets/v2-372dc6c567ba53a1e4559fdb0cb6b206_720w.jpg" srcset="/img/loading.gif" lazyload alt="img"></p>
<ul>
<li>s[0:5] == p[0:5]   在位置5处失败</li>
<li>那么,从s[1] s[2]  s[3]  开始的匹配,有咩有可能成功?
<ul>
<li>s[1] 不可能 :  s[1] == p[1] == ‘b’  != p[0]</li>
<li>s[2] : s[2] == p[2] != p[0]     c!=a</li>
</ul>
</li>
</ul>
<h3 id="22-next数组"><a class="markdownIt-Anchor" href="#22-next数组"></a> 2.2 next数组</h3>
<blockquote>
<p>对于模式串P而言, P 的 next 数组定义为：</p>
<ul>
<li>next[i] 表示 P[0] ~ P[i] 这一个子串，使得 <strong>前k个字符</strong>恰等于<strong>后k个字符</strong> 的最大的k.</li>
<li>P[0] 到 P[i] 这一段子串中，前next[i]个字符与后next[i]个字符一模一样</li>
</ul>
</blockquote>
<p><img src="/img/20220407-Leetcode796-KMP%E7%AE%97%E6%B3%95.assets/v2-49c7168b5184cc1744459f325e426a4a_720w.jpg" srcset="/img/loading.gif" lazyload alt="img"></p>
<ul>
<li>解释:
<ul>
<li>abca: 对最后的’a’来说,在这一子串中,重复子串只有’a’,所以next[3]=1</li>
<li>abcab: 重复子串有’ab’,所以next[4]=2</li>
</ul>
</li>
<li>有了重复子串,当abca…匹配失败,则下一次匹配直接跳到下一个以’ab’为开头的地方(即,最大前缀的位置)重新匹配</li>
</ul>
<h3 id="23-利用next"><a class="markdownIt-Anchor" href="#23-利用next"></a> 2.3 利用next</h3>
<p><img src="/img/20220407-Leetcode796-KMP%E7%AE%97%E6%B3%95.assets/v2-d6c6d433813595dce5aad08b40dc0b72_720w.jpg" srcset="/img/loading.gif" lazyload alt="img"></p>
<ul>
<li>匹配过程:
<ul>
<li>在 S[0] 尝试匹配，失配于 S[3] &lt;=&gt; P[3] 之后，我们直接把模式串往右移了两位，让 S[3] 对准 P[1]. 接着继续匹配，失配于 S[8] &lt;=&gt; P[6],</li>
<li>接下来我们把 P 往右平移了三位，把 S[8] 对准 P[3]. 此后继续匹配直到成功。</li>
</ul>
</li>
</ul>
<p>我们应该如何移动这把标尺？<strong>很明显，如图中蓝色箭头所示，旧的后缀要与新的前缀一致</strong></p>
<ul>
<li>回忆next数组的性质：P[0] 到 P[i] 这一段子串中，前next[i]个字符与后next[i]个字符一模一样.既然如此，如果失配在 P[r], 那么P[0]~P[r-1]这一段里面，<strong>前next[r-1]个字符恰好和后next[r-1]个字符相等</strong>——也就是说，我们可以拿长度为 next[r-1] 的那一段前缀，来顶替当前后缀的位置，让匹配继续下去！</li>
</ul>
<h3 id="24-快速求next数组"><a class="markdownIt-Anchor" href="#24-快速求next数组"></a> 2.4 快速求next数组</h3>
<ul>
<li>
<p>根据定义求next :  O(m^2)</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// next[x]</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getNext</span><span class="hljs-params">(x)</span></span> <span class="hljs-type">int</span> &#123;<br>    <span class="hljs-keyword">for</span> i:=x;i&gt;=<span class="hljs-number">0</span>;i-- &#123;<br>        <span class="hljs-comment">// 前缀等于后缀  则返回</span><br>        <span class="hljs-keyword">if</span> p[<span class="hljs-number">0</span>:i] == p[x-i+<span class="hljs-number">1</span>:x+<span class="hljs-number">1</span>] &#123;<br>            <span class="hljs-keyword">return</span> i<br>        &#125;<br>    &#125;<br>    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span><br>&#125;<br></code></pre></td></tr></table></figure>
</li>
</ul>
<blockquote>
<p>核心：P自己与自己匹配</p>
</blockquote>
<ul>
<li>定义 “k-前缀” 为一个字符串的前 k 个字符； “k-后缀” 为一个字符串的后 k 个字符。k 必须小于字符串长度。</li>
<li>next[x] 定义为： P[0]~P[x] 这一段字符串，使得<strong>k-前缀恰等于k-后缀</strong>的最大的k.</li>
</ul>
<blockquote>
<p>递推公式求next</p>
</blockquote>
<ul>
<li>P[x] == P[now]</li>
</ul>
<p><img src="/img/20220407-Leetcode796-KMP%E7%AE%97%E6%B3%95.assets/v2-6d6a40331cd9e44bfccd27ac5a764618_720w.jpg" srcset="/img/loading.gif" lazyload alt="img"></p>
<p>​	已经知道了 next[x-1]（以下记为now）</p>
<p>​	如果 P[x] 与 P[now] 一样，那最长相等前后缀的长度就可以扩展一位，很明显 next[x] = now + 1.</p>
<ul>
<li>P[x] != P[now]</li>
</ul>
<p><img src="/img/20220407-Leetcode796-KMP%E7%AE%97%E6%B3%95.assets/v2-ce1d46a1e3603b07a13789b6ece6022f_720w.jpg" srcset="/img/loading.gif" lazyload alt="img"></p>
<p>​</p>
<p>​	如图。长度为 now 的子串 <code>A</code> 和子串 <code>B</code> 是 P[0]~P[x-1] 中最长的公共前后缀。可惜 A 右边的字符和 B 右边的那个字符不相等，next[x]不能改成 now+1 了。因此，我们应该<strong>缩短这个now</strong>，把它改成小一点的值，再来试试 P[x] 是否等于 P[now].</p>
<p>​	now该缩小到多少呢？不要让now缩小太多。因此，在保持“P[0]~P[x-1]的now-前缀仍然等于now-后缀”的前提下，让这个新的now尽可能大一点。</p>
<p>​	P[0]~P[x-1] 的公共前后缀，前缀一定落在串A里面、后缀一定落在串B里面。换句话讲：接下来now应该改成：使得 <strong>A的k-前缀</strong>等于<strong>B的k-后缀</strong> 的最大的k.<br>
​	一个非常强的性质——<strong>串A和串B是相同的</strong>！B的后缀等于A的后缀！因此，使得A的k-前缀等于B的k-后缀的最大的k，其实就是串A的最长公共前后缀的长度 —— next[now-1]！</p>
<p><img src="/img/20220407-Leetcode796-KMP%E7%AE%97%E6%B3%95.assets/v2-c5ff4faaab9c3e13690deb86d8d17d71_720w.jpg" srcset="/img/loading.gif" lazyload alt="img"></p>
<p>​</p>
<p>​	当P[now]与P[x]不相等的时候，我们需要缩小now——把now变成next[now-1]，直到P[now]=P[x]为止。P[now]=P[x]时，就可以直接向右扩展了。</p>
<p>​	next[x-1]（以下记为now），即已知条件，上一个next项</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">buildNext</span><span class="hljs-params">()</span></span> []<span class="hljs-type">int</span> &#123;<br>    next := []<span class="hljs-type">int</span>&#123;&#125;<br>    next = <span class="hljs-built_in">append</span>(next, <span class="hljs-number">0</span>)  <span class="hljs-comment">//next[0] = 0</span><br>    i = <span class="hljs-number">1</span><br>    now = <span class="hljs-number">0</span>  <span class="hljs-comment">//next[x-1]</span><br>    <br>    <span class="hljs-comment">//now 对应于next数组</span><br>    <span class="hljs-comment">// i对应于p串</span><br>    <br>    <span class="hljs-keyword">for</span> i &lt; <span class="hljs-built_in">len</span>(p) &#123;<br>        <span class="hljs-keyword">if</span> p[now] == p[i] &#123;<br>            <span class="hljs-comment">// 可以向后扩展一位</span><br>            now += <span class="hljs-number">1</span><br>            i++<br>            next = <span class="hljs-built_in">append</span>(next, now)<br>        &#125;<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> now!=<span class="hljs-number">0</span> &#123;<br>            <span class="hljs-comment">// 缩小now</span><br>            now = next[now<span class="hljs-number">-1</span>] <br>        &#125;<span class="hljs-keyword">else</span>&#123;<br>            <span class="hljs-comment">//now==0</span><br>            <span class="hljs-comment">// 无法再缩小</span><br>            next = <span class="hljs-built_in">append</span>(next, <span class="hljs-number">0</span>)<br>            i+=<span class="hljs-number">1</span><br>        &#125;<br>    &#125; <br>    <span class="hljs-keyword">return</span> next<br>&#125;<br></code></pre></td></tr></table></figure>
<h3 id="25-kmp完整算法"><a class="markdownIt-Anchor" href="#25-kmp完整算法"></a> 2.5 KMP完整算法</h3>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">var</span> s,p <span class="hljs-type">string</span> <br><span class="hljs-comment">// 假设已经完成对s p的初始化</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">buildNext</span><span class="hljs-params">()</span></span> []<span class="hljs-type">int</span> &#123;<br>    next := []<span class="hljs-type">int</span>&#123;&#125;<br>    next = <span class="hljs-built_in">append</span>(next, <span class="hljs-number">0</span>)  <span class="hljs-comment">//next[0] = 0</span><br>    i = <span class="hljs-number">1</span><br>    now = <span class="hljs-number">0</span>  <span class="hljs-comment">//next[x-1]</span><br>    <br>    <span class="hljs-comment">//now 对应于next数组</span><br>    <span class="hljs-comment">// i对应于p串</span><br>    <br>    <span class="hljs-keyword">for</span> i &lt; <span class="hljs-built_in">len</span>(p) &#123;<br>        <span class="hljs-keyword">if</span> p[now] == p[i] &#123;<br>            <span class="hljs-comment">// 可以向后扩展一位</span><br>            now += <span class="hljs-number">1</span><br>            i++<br>            next = <span class="hljs-built_in">append</span>(next, now)<br>        &#125;<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> now!=<span class="hljs-number">0</span> &#123;<br>            <span class="hljs-comment">// 缩小now</span><br>            now = next[now<span class="hljs-number">-1</span>] <br>        &#125;<span class="hljs-keyword">else</span>&#123;<br>            <span class="hljs-comment">//now==0</span><br>            <span class="hljs-comment">// 无法再缩小</span><br>            next = <span class="hljs-built_in">append</span>(next, <span class="hljs-number">0</span>)<br>            i+=<span class="hljs-number">1</span><br>        &#125;<br>    &#125; <br>    <span class="hljs-keyword">return</span> next<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">search</span><span class="hljs-params">()</span></span> &#123;<br>    tar := <span class="hljs-number">0</span>  <span class="hljs-comment">// 主串s中将要匹配的位置</span><br>    pos := <span class="hljs-number">0</span> <span class="hljs-comment">// 模式串中将要匹配的位置</span><br>    next := buildNext()<br>    <span class="hljs-keyword">for</span> tar &lt; <span class="hljs-built_in">len</span>(s) &#123;<br>        <span class="hljs-keyword">if</span> s[tar] == p[pos] &#123;<br>            tar++<br>            pos++<br>        &#125;<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> pos==<span class="hljs-number">0</span> &#123;  <span class="hljs-comment">// 失配，pos!=0</span><br>            <span class="hljs-comment">//根据next移动</span><br>            pos = next[pos<span class="hljs-number">-1</span>]<br>        &#125;<span class="hljs-keyword">else</span>&#123;<br>            <span class="hljs-comment">// 失配 且 pos==0</span><br>            tar +=<span class="hljs-number">1</span><br>        &#125;<br>        <span class="hljs-keyword">if</span> pos == <span class="hljs-built_in">len</span>(p) &#123;<br>            <span class="hljs-comment">// 匹配成功</span><br>            printf(tar-pos+<span class="hljs-number">1</span>)  <span class="hljs-comment">//内置函数</span><br>            pos = next[pos<span class="hljs-number">-1</span>]<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E7%AE%97%E6%B3%95/" class="category-chain-item">算法</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/KMP/">#KMP</a>
      
        <a href="/tags/%E5%AD%97%E7%AC%A6%E4%B8%B2/">#字符串</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Leetcode796.KMP算法</div>
      <div>http://example.com/2022/04/07/20220407-Leetcode796-KMP算法/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>叶飞</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年4月7日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/04/07/20220407-Docker%E7%BD%91%E7%BB%9C/" title="Docker网络">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Docker网络</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/04/06/20220406-RestfulAPI/" title="RestfulAPI">
                        <span class="hidden-mobile">RestfulAPI</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  


  
  









    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  
      <script>
        if (!window.MathJax) {
          window.MathJax = {
            tex    : {
              inlineMath: { '[+]': [['$', '$']] }
            },
            loader : {
              load: ['ui/lazy']
            },
            options: {
              renderActions: {
                insertedScript: [200, () => {
                  document.querySelectorAll('mjx-container').forEach(node => {
                    let target = node.parentNode;
                    if (target.nodeName.toLowerCase() === 'li') {
                      target.parentNode.classList.add('has-jax');
                    }
                  });
                }, '', false]
              }
            }
          };
        } else {
          MathJax.startup.document.state(0);
          MathJax.texReset();
          MathJax.typeset();
          MathJax.typesetPromise();
        }
      </script>
    

  <script  src="https://lib.baomitu.com/mathjax/3.2.1/es5/tex-mml-chtml.js" ></script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="/js/leancloud.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
